import { useState, useEffect, useRef,useMemo } from 'react'
import { Button, Form, message } from 'antd'
import { pinyin, convert } from "pinyin-pro";
import { CloseOutlined, MinusOutlined } from '@ant-design/icons'
import { useNavigate } from 'react-router-dom'
import { useDispatch, useSelector } from 'react-redux'
import bus from '../../utils/eventBus'
import { setUserInfo } from '../../store/modules/userReducer'
import './index.scss'
const Login = () => {
    const { isExpire,version } = useSelector((state: any) => state.licenseInfoReducer.licenseInfo)
    const licenseInfo = useSelector((state: any) => state.licenseInfoReducer.licenseInfo)
    const dispatch = useDispatch()
    const navigate = useNavigate()
    const dataList = useRef([
        {
            prop: "account",
            placeholder: "账号",
            type: "text",
        },
        {
            prop: "password",
            placeholder: "密码",
            type: "password",
        },
    ])
    const formRef = useRef<any>(null)
    const [loading, setLoading] = useState<boolean>(false)
    const [form] = Form.useForm()
    const handleLogin = () => {
        if(!Object.keys(licenseInfo).length) return message.info('应用初始化中,请稍后...')
        formRef.current.validateFields().then((res: any) => {
            const { account, password } = res
            if (!account && !password) {
                message.warning('账号密码不能为空！！！')
                return
            }
            const params = {
                chineseName:
                    convert(pinyin(account, { type: 'array' }).join(""), { format: 'toneNone' }) === account
                        ? ""
                        : account,
                name: convert(pinyin(account, { type: 'array' }).join(""), { format: 'toneNone' }),
                passwd: password,
                isExpire,
            }
            setLoading(true)
            window.chromePro.tryLogin(
                JSON.stringify(params)
            );
        })
    }
    const handleMinWin = () => {
        window.chromePro.winMin();
    }
    const handleClose = () => {
        window.chromePro.appExit();
    }
    const handleKeyUp = (e: any, type: string) => {
        if (type === 'password' && e.key === "Enter") {
            handleLogin()
        }
    }
    const tryLoginFinished = (res: any) => {
        setLoading(false)
        if (res.code === 200) {
            dispatch(setUserInfo(res.data))
            // window.chromePro.getConfig();
            const { name, userType } = res.data
            const params = {
                oper: name,
                userType,
                opType: "登录",
                opDetail: "登录成功！",
                status: 1,
            }
            window.chromePro.addOpLog(
                JSON.stringify(params)
            );
            navigate('/layout')
        } else {
            message.error(res.msg || '登录失败！')
        }
    }
    const getConfigFinished = (res: any) => {
        if (res.code === 200) {

        }
    }
    const loaded = () => {
        window.chromePro.checkAuthorizeFile();
    }
    useEffect(() => {
        try {
            window.chromePro.checkAuthorizeFile();
        } catch { }
        bus.addListener('loaded', loaded)
        bus.addListener('tryLoginFinished', tryLoginFinished)
        bus.addListener('getConfigFinished', getConfigFinished)
    }, [])
    useEffect(() => {
        return () => {
            bus.addListener('loaded', loaded)
            bus.removeListener('tryLoginFinished', tryLoginFinished)
            bus.removeListener('getConfigFinished', getConfigFinished)
        }
    }, [])
    return (
        <>
            <div className='login-box'>
                <div className="login-form">
                    <div className="login-header">
                        <img draggable="false" style={{ height: '36px' }} src={require('../../assets/network/logo.png')} alt="" />
                        <span className="text-login">集中文印单机版</span>
                    </div>
                    <Form ref={formRef} style={{ marginTop: "60px" }} form={form}>
                        {dataList.current.map(item => {
                            return <Form.Item name={item.prop} key={item.prop}>
                                <div className="input-outline-x">
                                    <input onKeyUp={(e) => handleKeyUp(e, item.type)} type={item.type} className="input-control input-outline"
                                        placeholder={item.placeholder} />
                                    <label className="input-label">{item.placeholder}</label>
                                </div>
                            </Form.Item>
                        })}
                    </Form>
                    <div className="footer">
                        <Button loading={loading} type="primary" onClick={handleLogin} className="footer-btn">登录</Button>
                    </div>
                    <div className="bottom-tips">
                        <div className="line"></div>
                        <span className="line-span">支持刷卡、指纹认证登录</span>
                    </div>
                </div>
                <div className="icon-min" onClick={handleMinWin}>
                    <MinusOutlined style={{ fontSize: '20px', color: '#8e8e93' }} className="el-icon-minus" />
                </div>
                <div className="icon-close" onClick={handleClose}>
                    <CloseOutlined style={{ fontSize: '26px', color: '#8e8e93' }} className="el-icon-close" />
                </div>
                <span className="version">版本V{version}</span>
            </div>
        </>
    )
}
export default Login